package dLogistic.domain.model.sharedValueObjects;


import dLogistic.domain.service.GeolokalizacjaService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.ArrayList;

/**
 * Created by Przemek on 2014-10-23.
 */
@Entity
@Table(name = "Adres")
public class Adres {

    @Id
    private String uuid;    //uuid

    private String ulica;
    private String numerDomu;
    private String numerLokalu;

    private String miasto;
    private String kodPocztowy;

    private Double longitude;
    private Double latitude;

    private Integer typ;

    private String uuid_parent;

    protected static SessionFactory factory;

    public String uuid(){
        return uuid;
    }
    public Double longitude(){
        return longitude;
    }
    public Double latitude(){
        return latitude;
    }
    public String uuid_parent(){
        return uuid_parent;
    }

    public Adres(String ulica, String numerDomu, String numerLokalu, String miasto, String kodPocztowy, String uuid, String uuid_parent, Integer typ){
        this.ulica = ulica;
        this.numerDomu = numerDomu;
        this.numerLokalu = numerLokalu;
        this.miasto = miasto;
        this.kodPocztowy = kodPocztowy;
        this.uuid_parent = uuid_parent;
        this.typ = typ;

        this.uuid = uuid;

        GeolokalizacjaService geo = new GeolokalizacjaService();
        ArrayList geoLok = geo.wyznaczGeolokalizacje(this.ulica, this.numerDomu,this.numerLokalu,this.miasto,this.kodPocztowy);
        this.latitude = Double.parseDouble(geoLok.get(0).toString());
        this.longitude = Double.parseDouble(geoLok.get(1).toString());

        try{
            factory = new Configuration().configure("/resources/hibernate.cfg.xml").buildSessionFactory();
        }catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        Session session = factory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        session.saveOrUpdate(this);
        transaction.commit();

    }

    public Adres(){

    }
}


